package com.lzb.video;

import android.Manifest;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzb.video.utils.CameraHelpUtil;
import com.lzb.video.utils.MediaRecorderHelpUtil;

import java.io.File;

public class RecorderVideoActivity extends AppCompatActivity {

    private String filePath = " ";
    private Camera camera;
    private CamcorderProfile profile;
    private MediaRecorder mediaRecorder;
    private SurfaceView surfaceView;
    private ImageView img_start;
    /** true 正在录制 */
    private boolean isRecoding = false;
    private TextView txt_play;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder_video);
        surfaceView = (SurfaceView) findViewById(R.id.sufaceview);
        img_start = (ImageView) findViewById(R.id.img_start);
        txt_play = (TextView) findViewById(R.id.txt_play);
        setListener();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (camera != null){
                    CameraHelpUtil.startPreview(camera,surfaceView.getHolder());
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (camera != null){
                    camera.stopPreview();
                }
            }
        });

        img_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (camera == null){
                    return;
                }
                if (isRecoding){
                    isRecoding = false;
                    MediaRecorderHelpUtil.stop(mediaRecorder);
                    img_start.setImageResource(R.mipmap.icon_voice_transcribe);
                }else {
                    mediaRecorder = MediaRecorderHelpUtil.record(camera,profile,filePath,surfaceView.getHolder());
                    isRecoding = true;
                    img_start.setImageResource(R.mipmap.icon_stop_transcribe);
                }
            }
        });

        txt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play();
            }
        });
    }

    private void play() {
        if (null == MediaRecorderHelpUtil.getFile()){
            return;
        }
        Intent intent = new Intent(this,MediaPlayerSurfaceActivity.class);
        intent.putExtra("video_Path",MediaRecorderHelpUtil.getFile().getAbsolutePath());
        startActivity(intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        isRecoding = false;
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (camera == null){
            checkPermission();
        }
    }

    /**
     * 动态检测必要的权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            initDrives();
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != 0 ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0 ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != 0 ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != 0){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA},0x123);
        }else {
            initDrives();
        }
    }

    /**
     * 初始化摄像头设备
     */
    private void initDrives() {
        getFilePath();
        camera = CameraHelpUtil.open();
        //打开锁 ，使其他线程无法访问 摄像头
        camera.lock();
        if (camera != null){
            profile = CameraHelpUtil.setCamcorderProfile(false);
            CameraHelpUtil.setCameraParameters(camera,profile,null,null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x123){
            if (grantResults[0] == 0 && grantResults[1] == 0 && grantResults[2] == 0 && grantResults[3] == 0){
                initDrives();
            }else {
                Toast.makeText(this, "需要必要的权限，请授权", Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 获取文件保存路径
     */
    private void  getFilePath(){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            filePath  = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() /*+ File.separator + getPackageName()*/;
        }else {
            filePath = Environment.getDataDirectory().getAbsolutePath() /*+ File.separator + getPackageName()*/;
        }
        filePath = filePath + File.separator + "Camera";
        File file = new File(filePath);
        if (!file.exists()){
            file.mkdirs();
        }
        filePath = file.getAbsolutePath();
    }


    @Override
    protected void onDestroy() {
        CameraHelpUtil.releaseCamera(camera);
        if (isRecoding){
            MediaRecorderHelpUtil.stop(mediaRecorder);
//            MediaRecorderHelpUtil.release(mediaRecorder);
        }
        super.onDestroy();
    }
}
